package utils

import (
	"github.com/go-git/go-git/v5"
	"github.com/go-git/go-git/v5/plumbing"
	gitHttp "github.com/go-git/go-git/v5/plumbing/transport/http"
	"log"
	"os"
	"path/filepath"
)

type Gitlab struct {
	Path     string `yaml:"repo"` // Path Git路径
	Branch   string `yaml:"branch"`  // Branch 分支
	Remote   string `yaml:"remote"`  // RemoteName 远程源
	Username string `yaml:"uid"` // Username 用户名
	Password string `yaml:"pwd"` // Password 密码
}

func (that *Gitlab) Pull() {
	that.Path, _ = filepath.Abs(that.Path)
	CFBDecryptByRef(&that.Username)
	CFBDecryptByRef(&that.Password)

	log.Println("cd", that.Path) // 参数中间会补全空格
	repo, err := git.PlainOpen(that.Path)
	if err != nil {
		log.Fatalln(">>> 打开本地git仓库失败 ->", err)
	}

	// Get the working directory for the repository
	wt, err := repo.Worktree()
	if err != nil {
		log.Fatalln(">>> 获取本地工作树失败 ->", err)
	}

	log.Println("git checkout .")
	branch := plumbing.NewBranchReferenceName(that.Branch)
	err = wt.Checkout(&git.CheckoutOptions{Force: true, Branch: branch})
	if err != nil {
		log.Fatalln(">>> 检出本地git代码失败 ->", err)
	}

	log.Println("git pull")
	// Pull the latest changes from the origin remote and merge into the current branch
	err = wt.Pull(&git.PullOptions{
		RemoteName: that.Remote,
		Progress:   os.Stdout,
		Auth: &gitHttp.BasicAuth{
			Username: that.Username, // anything except an empty string
			Password: that.Password,
		}})

	switch err {
	case nil:
		log.Println(">>> 拉取远程git代码成功")
		break
	case git.NoErrAlreadyUpToDate:
		log.Println(">>> 拉取远程git代码成功:", err)
		break
	default:
		log.Fatalln(">>> 拉取远程git代码失败 ->", err)
		break
	}
}
